<script lang="ts" setup>
import { useRoute } from 'vue-router'
import { computed } from 'vue'
import type { RequestOption } from '@arco-design/web-vue/es/upload/interfaces'
import { Message } from '@arco-design/web-vue'
import { LabID } from '@/constants/lab'
import { AllFileAccept } from '@/constants/file-accept'
import { useGetUploadURL } from '@/apis/lab/composables'
import { useUpload } from '@/composables/useUpload'

const route = useRoute()

const { data } = useGetUploadURL(
  computed(() => ({
    classID: +route.params.classID,
    experimentID: LabID.ReportUpload
  }))
)

const handleUpload = (options: RequestOption) => {
  const { onProgress, onError, onSuccess, fileItem } = options

  if (data.value === null) {
    return
  }

  const {
    onError: uploadOnError,
    onSuccess: uploadOnSuccess,
    onProgress: uploadOnProgress,
    abort
  } = useUpload(data.value.url, fileItem.file)

  uploadOnProgress(onProgress)
  uploadOnSuccess((res) => {
    Message.success({ content: '上传成功' })
    onSuccess(res)
  })
  uploadOnError(onError)

  return { abort }
}
</script>

<template>
  <MarkdownReader>
    <RouterView />
    <template #markdown-footer>
      <div class="card my-xs">
        <h2 class="card-title mb-xs">文件上传</h2>
        <a-upload
          :action="data?.url"
          draggable
          :accept="AllFileAccept"
          :custom-request="handleUpload"
          :limit="1"
        >
          <template #upload-button>
            <div>
              <div
                class="pa-xl bg-arco-gray-2 border-1 rounded border-dashed border-arco-4 flex justify-center items-center gap-xs"
              >
                <VscodeIconsFileTypeWord class="text-xl" />
                拖拽或选择文件上传
              </div>
            </div>
          </template>
        </a-upload>
      </div>
    </template>
  </MarkdownReader>
</template>
